from django import forms
from datetime import datetime
from django.db import transaction
from django.contrib import messages
from django.shortcuts import render, redirect
from django.core.validators import RegexValidator

from www import models
from utils.bootstrap import BootStrapForm


class CouponForm(BootStrapForm):
    code = forms.CharField(label="优惠券")
    phone = forms.CharField(label="绑定手机", validators=[RegexValidator(r'^\d{11}$', '手机号格式错误')])


def coupon(request):
    if not request.user:
        return redirect("wx_login")

    if request.method == 'GET':
        form = CouponForm()
        return render(request, "coupon.html", {"form": form})

    # 1.表单验证
    form = CouponForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'coupon.html', {"form": form})

    # 2.提取手机号和优惠券
    code = form.cleaned_data['code']
    phone = form.cleaned_data['phone']

    # 3.优惠券的校验（优惠券表+用户表）
    try:
        with transaction.atomic():
            instance = models.Coupon.objects.filter(code=code, status=0).only("id").select_for_update().first()
            if not instance:
                form.add_error("code", "优惠券已失效")
                return render(request, 'coupon.html', {"form": form})

            instance.status = 1
            instance.user_id = request.user.id
            instance.save()
            models.User.objects.filter(id=request.user.id).update(user_type=1, phone=phone, vip_date=datetime.now())
    except Exception as e:
        transaction.rollback()
        form.add_error("code", "兑换失败")
        return render(request, 'coupon.html', {"form": form})

    transaction.commit()
    messages.add_message(request, messages.SUCCESS, "兑换成功，快去学习吧！")
    request.session['user']['user_type'] = 1
    return redirect("coupon")
